<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>商品列表</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        h1 {
            text-align: center;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }

        th,
        td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        tr:hover {
            background-color: #f1f1f1;
        }

        img {
            max-width: 100px;
            height: auto;
        }

        .pagination {
            display: flex;
            justify-content: center;
            list-style: none;
            padding: 0;
        }

        .pagination li {
            margin: 0 5px;
        }

        .pagination a {
            text-decoration: none;
            padding: 8px 16px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: #f2f2f2;
            color: #333;
        }

        .pagination a:hover {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
        }

        .pagination a.active {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
        }

        .pagination-select {
            padding: 5px 10px;
            border-radius: 5px;
            width: 160px;
            text-align: center;
            margin: 0 auto;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .pagination-select label {
            margin-right: 10px;
        }

        .pagination-select select {
            padding: 5px 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            width: 60px;
        }

        .search-bar {
            margin-bottom: 20px;
            text-align: left;
        }

        .search-bar input {
            width: 300px;
            margin-right: 10px;
            padding: 10px;
            font-size: 16px;
            border: 2px solid #ccc;
            border-radius: 5px;
        }

        .search-bar input:focus {
            border-color: #007bff;
            box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
        }

        .status-normal {
            color: green;
        }

        .status-unavailable {
            color: red;
        }

        /* 对话框样式 */
        dialog {
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
        }

        form {
            display: flex;
            flex-direction: column;
        }

        label {
            margin-bottom: 5px;
        }

        input,
        select {
            margin-bottom: 10px;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 3px;
        }

        button {
            padding: 8px 15px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }

        button.cancel {
            background-color: #ccc;
        }
    </style>
</head>

<body>
<div class="search-bar">
    <input type="text" id="searchInput" placeholder="请输入商品关键字" class="form-control">
</div>

<div class="btach-action">
    <button id="batchDelBtn" class="btn btn-danger">批量下架</button>
</div>

<table class="table table-bordered">
    <thead>

    <tr>
        <th><input type="checkbox" id="selectAll"></th>
        <th>ID</th>
        <th>标题</th>
        <th>描述</th>
        <th>价格</th>
        <th>图片</th>
        <th>状态</th>
        <th>商家</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody id="goodsTableBody">
    </tbody>
</table>

<div class="pagination-select">
    <label for="pageSizeSelect">每页显示:</label>
    <select id="pageSizeSelect" class="form-control">
        <option value="2">2</option>
        <option value="5" selected>5</option>
        <option value="10">10</option>
        <option value="15">15</option>
    </select>
</div>

<ul class="pagination" id="pagination">

</ul>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        let currentPage = 1;
        const mid = localStorage.getItem("mid");
        const mname = localStorage.getItem("mname");
        let size = parseInt(document.getElementById('pageSizeSelect').value);
        let searchKeyword = ''; // 搜索关键字变量

        //分页器初始化
        function generatePagination(currentPage, totalPages) {

            const pagination = document.getElementById('pagination');
            paginationnnerHTML = '';

            const prevLi = document.createElement('li');
            const prevA = document.createElement('a');
            prevA.textContent = '上一页.i';
            prevA.className = 'page-link';
            prevA.onclick = function () {
                if (currentPage > 1) {
                    loadGoodsData(currentPage - 1, mid, size, searchKeyword);
                }
            };
            if (currentPage === 1) {
                prevA.style.pointerEvents = 'none';
                prevA.style.opacity = '0.5';
            }
            prevLi.appendChild(prevA);
            pagination.appendChild(prevLi);

            for (let i = 1; i <= totalPages; i++) {
                const li = document.createElement('li');
                const a = document.createElement('a');
                a.textContent = i;
                a.className = 'page-link';
                a.onclick = function () {
                    loadGoodsData(i, mid, size, searchKeyword);
                };
                if (i === currentPage) {
                    a.classList.add('active');
                }
                li.appendChild(a);
                pagination.appendChild(li);
            }

            const nextLi = document.createElement('li');
            const nextA = document.createElement('a');
            nextA.textContent = '下一页';
            nextA.className = 'page-link';
            nextA.onclick = function () {
                if (currentPage < totalPages) {
                    loadGoodsData(currentPage + 1, mid, size, searchKeyword);
                }
            };
            if (currentPage === totalPages) {
                nextA.style.pointerEvents = 'none';
                nextA.style.opacity = '0.5';
            }
            nextLi.appendChild(nextA);
            pagination.appendChild(nextLi);
        }

        function loadGoodsData(page, mid, size, keyword) {
            currentPage = page;
            let url = `/goods_func/getGoodsPg?page=${page}&size=${size}&mid=${mid}`;
            if (keyword) {
                url = `/goods_func/getGoodsByTitle?keyword=${keyword}&mid=${mid}`;
            }
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        const tableBody = document.getElementById('goodsTableBody');
                        tableBody.innerHTML = '';
                        data.data.forEach(goods => {
                            const row = document.createElement('tr');
                            const statusText = goods.state === 0? '正常销售' : '已下架';
                            const statusClass = goods.state === 0? 'status-normal' : 'status-unavailable';
                            row.innerHTML = `
                            <td><input type="checkbox" class="checkbox" data-id="${goods.id}"></td>
                            <td>${goods.id}</td>
                            <td>${goods.title}</td>
                            <td>${goods.descr}</td>
                            <td>${goods.price}</td>
                            <td><img src="${goods.img}" alt="商品图片" width="100" height="100"/></td>
                            <td class="${statusClass}">${statusText}</td>
                            <td>${mname}</td>
                            <td>
                                <button class="btn btn-primary edit-btn"
                                        data-id="${goods.id}"
                                        data-title="${goods.title}"
                                        data-descr="${goods.descr}"
                                        data-price="${goods.price}"
                                        data-img="${goods.img}"
                                        data-state="${goods.state}">编辑</button>
                                <button class="btn btn-danger delete-btn" data-id="${goods.id}">下架</button>
                            </td>
                        `;
                            tableBody.appendChild(row);
                        });

                        //重新绑定全选 反选
                        document.getElementById('selectAll').addEventListener('change', function () {
                            const isChecked = this.checked;
                            document.querySelectorAll('.checkbox').forEach(checkbox => {
                                checkbox.checked = isChecked;
                            })
                        })

                        const editButtons = document.querySelectorAll('.edit-btn');
                        editButtons.forEach(button => {
                            button.addEventListener('click', function () {
                                const goodsId = this.getAttribute('data-id');
                                const goodsTitle = this.getAttribute('data-title');
                                const goodsDescr = this.getAttribute('data-descr');
                                const goodsPrice = this.getAttribute('data-price');
                                const goodsImg = this.getAttribute('data-img');
                                const goodsState = this.getAttribute('data-state');

                                // 创建并显示对话框
                                const dialog = document.createElement('dialog');
                                dialog.innerHTML = `
                                        <form>
                                            <label for="edit-title">标题:</label>
                                            <input type="text" id="edit-title" value="${goodsTitle}">
                                            <label for="edit-descr">描述:</label>
                                            <input type="text" id="edit-descr" value="${goodsDescr}">
                                            <label for="edit-price">价格:</label>
                                            <input type="text" id="edit-price" value="${goodsPrice}">
                                            <label for="edit-img">图片:</label>
                                            <img id="edit-img-preview" src="${goodsImg}" alt="商品图片" style="max-width: 100px; height: auto; margin-bottom: 5px;">
                                            <input type="file" id="edit-img-file" accept="image/*">
                                            <label for="edit-state">状态:</label>
                                            <select id="edit-state">
                                                <option value="0" ${goodsState === '0'? 'selected' : ''}>正常销售</option>
                                                <option value="1" ${goodsState === '1'? 'selected' : ''}>已下架</option>
                                            </select>
                                            <button type="submit" class="save-btn">保存</button>
                                            <button type="button" class="cancel-btn">取消</button>
                                        </form>
                                    `;
                                document.body.appendChild(dialog);
                                dialog.showModal();

                                const saveButton = dialog.querySelector('.save-btn');
                                const cancelButton = dialog.querySelector('.cancel-btn');
                                const imgInput = dialog.querySelector('#edit-img-file');

                                imgInput.addEventListener('change', function (e) {
                                    const file = e.target.files[0];
                                    if (file) {
                                        const reader = new FileReader();
                                        reader.onload = function (event) {
                                            const imgPreview = dialog.querySelector('#edit-img-preview');
                                            imgPreview.src = event.target.result;
                                        };
                                        reader.readAsDataURL(file);
                                    }
                                });

                                saveButton.addEventListener('click', function () {
                                    const newTitle = document.getElementById('edit-title').value;
                                    const newDescr = document.getElementById('edit-descr').value;
                                    const newPrice = document.getElementById('edit-price').value;
                                    const newState = document.getElementById('edit-state').value;

                                    const fileInput = document.getElementById('edit-img-file');
                                    const formData = new FormData();
                                    formData.append('id', goodsId);
                                    formData.append('title', newTitle);
                                    formData.append('descr', newDescr);
                                    formData.append('price', newPrice);
                                    formData.append('state', newState);
                                    console.log(formData);
                                    if (fileInput.files && fileInput.files.length > 0) {
                                        formData.append('file', fileInput.files[0]);
                                    }

                                    fetch(`/goods_func/updateGoodInfo`, {
                                        method: 'POST',
                                        body: formData
                                    })
                                        .then(response => response.json())
                                        .then(data => {
                                            if (data.code === 200) {
                                                alert('商品信息已更新');
                                                dialog.close();
                                                loadGoodsData(currentPage, mid, size, searchKeyword);
                                            } else {
                                                console.error('Error:', data.msg);
                                                alert('更新失败');
                                            }
                                        })
                                        .catch(error => console.error('Error:', error));
                                });

                                cancelButton.addEventListener('click', function () {
                                    dialog.close();
                                });
                            });
                        });

                        // 添加下架按钮点击事件
                        const deleteButtons = document.querySelectorAll('.delete-btn');
                        deleteButtons.forEach(button => {
                            button.addEventListener('click', function () {
                                const goodsId = this.getAttribute('data-id');
                                // 处理下架逻辑
                                if (confirm('确定要下架该商品吗？')) {
                                    const formData = new URLSearchParams();
                                    formData.append('id', goodsId);
                                    formData.append('state', 1);

                                    fetch(`/goods_func/updateGood`, {
                                        method: 'POST',
                                        headers: {
                                            'Content-Type': 'application/x-www-form-urlencoded'
                                        },
                                        body: formData.toString()
                                    })
                                        .then(response => response.json())
                                        .then(data => {
                                            if (data.code === 200) {
                                                alert('商品已下架');
                                                loadGoodsData(currentPage, mid, size, searchKeyword);
                                            } else {
                                                console.error('Error:', data.msg);
                                                alert('下架失败');
                                            }
                                        })
                                        .catch(error => console.error('Error:', error));
                                }
                            });
                        });

                        const totalPages = Math.ceil(data.data1 / size);
                        generatePagination(page, totalPages);
                    } else {
                        console.error('Error:', data.msg);
                    }
                })
                .catch(error => console.error('Error:', error));
        }

        document.getElementById('pageSizeSelect').addEventListener('change', function () {
            size = parseInt(this.value);
            loadGoodsData(currentPage, mid, size, searchKeyword);
        });

        document.getElementById('searchInput').addEventListener('input', function () {
            searchKeyword = this.value.trim();
            console.log(searchKeyword);
            currentPage = 1; // 重置当前页码
            loadGoodsData(currentPage, mid, size, searchKeyword);
        });

        document.getElementById('selectAll').addEventListener('change',function (){
            const isChecked = this.checked;
            document.querySelectorAll('.checkbox').forEach(checkbox => {
                checkbox.checked = isChecked;
            })
        })

        // 批量下架
        document.getElementById('batchDelBtn').addEventListener('click',function(){
            const selectIds=[];
            document.querySelectorAll('.checkbox:checked').forEach(checkbox=>{
                selectIds.push(checkbox.getAttribute('data-id'));
            });
            if(selectIds.length === 0){
                alert('请选择要下架的商品');
                return;
            }
            if(confirm('确定要下架选中的商品吗？')){
                fetch('/goods_func/updateBatch',{
                    method:'POST',
                    headers:{
                        'Content-type':'application/json'
                    },
                    body:JSON.stringify(selectIds)
                })
                    .then(res=>res.json())
                    .then(data=>{
                        if(data.code === 200){
                            alert('商品已下架');
                            loadGoodsData(currentPage, mid, size, searchKeyword);
                        }else{
                            console.error('Error:', data.msg);
                            alert('下架失败');
                        }
                    })
                    .catch(error =>{
                        alert('下架失败');
                        console.error('Error:', error);
                    });
            }
        })

        loadGoodsData(currentPage, mid, size, searchKeyword);
    });
</script>
</body>

</html>